package com.oocl.o2o.client.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.client.dao.FoodDao;
import com.oocl.o2o.client.entity.Food;
import com.oocl.o2o.client.entity.FoodType;

/**
 * @description: 
 * @author  XIEMI2
 * @date Aug 12, 2017 7:32:08 PM
 * @version 1.0
 */
@Repository(value="foodDao")
public class FoodDaoImpl implements FoodDao{

	@PersistenceContext(name="un")
	private EntityManager em;
	
	@Override
	public Food add(Food food) {
		em.persist(food);
		return food;
	}

	@Override
	public Food delete(String id) {
		Food food = em.find(Food.class, id);
		em.remove(food);
		return food;
	}

	@Override
	public Food update(Food food) {
		em.find(Food.class, food.getId());
		em.clear();
		em.merge(food);
		return food;
	}

	@Override
	public Food findById(String id) {
		Food food = em.find(Food.class, id);
		return food;
	}

	@Override
	public List<Food> findByMerchantId(String merchantId) {
		String jpql = "from Food f where f.merchant.id =:merchantId";
		List<Food> foods = em.createQuery(jpql).setParameter("merchantId", merchantId).getResultList();
		return foods;
	}

	
	
	
	@Override
	public List<Food> findByTypeId(String typeId) {
		String jpql = "from Food f where f.foodType.id =:typeId";
		List<Food> foods = em.createQuery(jpql).setParameter("typeId", typeId).getResultList();
		return foods;
	}

	@Override
	public List<Food> findAll() {
		String jpql = "from Food";
		List<Food> foods = em.createQuery(jpql).getResultList();
		return foods;
	}
	
	@Override
	public List<Food> findByTypeIdAndMerchantId(String typeId, String merchantId) {
		String jpql = "from Food f where f.foodType.id =:typeId and f.merchant.id =:merchantId";
		List<Food> foods = em.createQuery(jpql).setParameter("typeId", typeId).setParameter("merchantId", merchantId).getResultList();
		return foods;
	}

	@Override
	public List<Food> findByFoodKeyWord(String keyWord) {
		String jpql = "from Food f where f.name like :keyWord";
		List<Food> foods = em.createQuery(jpql).setParameter("keyWord", "%"+keyWord+"%").getResultList();
		return foods;
	}

	@Override
	public List<Food> findByMerchantName(String merchantName) {
		String jpql = "from Food f where f.merchant.username =:merchantName";
		List<Food> foods = em.createQuery(jpql).setParameter("merchantName", merchantName).getResultList();
		return foods;
	}
	
}


